%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Leistung hinter Polstrahlteiler nach Manipulation mit \lambda/2 oder /4 Plättchen.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function PolarisationsVermessung
figure(1);

X=[0:30:360];																	%in um
P=[2.65 2.64 2.63 2.62 2.51 2.26 1.84 1.31 0.78 0.37 0.14 0.04 0.01];
P=max(P)-P;
P=P/max(P);

param_0=[200 110];															    %starting values: guessed waist and position of center
%v=optimset('TolX',1e-6,'TolFun',1e-6,'MaxIter',1e6,'MaxFunEvals',1e6);         %start least squares fit
pa=fminsearch(@erfc_fit2,param_0,[],X,P)

subplot(222),polar(X,P,'-+r')%,X, 1/2*erf(sqrt(2)*(X-pa(2))/pa(1))+.5,'b','LineWidth',1.4);
set(gca,'FontSize',16,'LineWidth',1.4);
xlabel('{\itz}   (\mum)');
ylabel('{\itP}   (mW)')
title(['{\itw}_0 = ',num2str(pa(1)),' \mum']);


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Chi Quadrat Minimierung
%  pa(1) : w0		und		pa(2) : center position

function chi = erfc_fit2(pa,data_x,data_y);

x = data_x;
y = data_y;
a = 1+cos(data_x);				%(y - (1/2*erf(sqrt(2)*(x-pa(2))/pa(1))+.5)).^2;
chi = sqrt(sum(a) / length(x));

subplot(222),plot(x,y,'+r',x, 1/2*erf(sqrt(2)*(x-pa(2))/pa(1))+.5,'b','LineWidth',1.4);
set(gca,'FontSize',16,'LineWidth',1.4);
xlabel('{\itz}   (\mum)');
ylabel('{\itP}   (mW)')
title(['{\itw}_0 = ',num2str(pa(1)),' \mum']);
pause(.01);